#include "threadPool.h"

int recvFile(int netfd)
{
    // 先收第一个小火车，火车名
    chdir("../serverFolder");
    train_t train;
    bzero(&train, sizeof(train));
    recv(netfd, &train.length, sizeof(int), 0);
    recv(netfd, train.data, train.length, 0);
    // 先将文件名拓展为*.filepart
    char buf0[20] = "";
    strcpy(buf0, train.data);
    // puts(buf0);
    strcat(train.data, ".filepart");
    char buf1[20] = "";
    strcpy(buf1, train.data);
    // puts(buf1);
    int fd;
    off_t filesize = 0;
    off_t offset = 0;
    off_t recvSize = 0;
    int existFlag = 0;
    if (open(train.data, O_RDWR, 0666))
    {
        fd = open(train.data, O_RDWR | O_CREAT, 0666);
        struct stat statbuf;
        fstat(fd, &statbuf);
        offset = statbuf.st_size;
        lseek(fd, offset, SEEK_SET);
        existFlag = 1;
        send(netfd, &existFlag, sizeof(existFlag), 0);
        send(netfd, &offset, sizeof(offset), 0);
    }
    else
    {
        fd = open(train.data, O_RDWR | O_CREAT, 0666);
        send(netfd, &existFlag, sizeof(existFlag), 0);
    }

    // 第二辆火车，火车的长度
    recv(netfd, &train.length, sizeof(int), 0);
    recv(netfd, train.data, train.length, 0);
    memcpy(&filesize, train.data, train.length);
    printf("offset = %lld\n", (long long)offset);
    printf("total recvSize = %lld\n", (long long)filesize);
    //  分批接收
    long curSize = 0;
    long lastSize = 0; // 上一次显示进度时候的文件大小
    long slice = filesize / 1000;
    while (1)
    {
        bzero(&train, sizeof(train));
        // recv(netfd,&train.length,sizeof(int),MSG_WAITALL);
        recvn(netfd, &train.length, sizeof(int));
        if (train.length != 1000)
        {
            printf("train.length = %d\n", train.length);
        }
        if (train.length == 0)
        {
            break; // 说文件已经发完了
        }
        // recv(netfd,train.data,train.length,MSG_WAITALL);
        recvn(netfd, train.data, train.length);
        write(fd, train.data, train.length);
        curSize += train.length;
        if (curSize - lastSize > slice)
        {
            printf("%5.2lf%%\r", 100.0 * curSize / filesize);
            fflush(stdout);
            lastSize = curSize;
        }
    }
    printf("100.00%%\n");
    int ret = rename(buf1, buf0);
    ERROR_CHECK(ret, -1, "rename");
    // 一次性接收
    //  ftruncate(fd,filesize);
    //  char *p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    //  ERROR_CHECK(p,MAP_FAILED,"mmap");
    //  recvn(netfd,p,filesize); //一次性收了一个文件的内容
    // //  munmap(p,filesize);
    unsigned char md[16]="";
    md5(buf0,md);
    unsigned char md1[16]="";
    recv(netfd,md1,sizeof(md1),0);
    for(int i = 0; i < 16;++i){
        printf("%02x", md1[i]);
    }
    printf("\n");
    if(memcmp(md,md1,sizeof(md1))==0){
        printf("recved file is correct\n");
    }else{
        printf("recved file is not correct\n");
        // log_INFO("recved file is not correct");
    }
    close(fd);
}